/*
 *    Copyright(c)2023-2024
 *    项目名称:hello-world
 *    文件名称:SysLoginLogServiceImpl.java
 *    Date:2023/11/26 下午7:23
 *    Author:赵士杰
 */

package com.hw.system.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hw.common.utils.bean.BeanCopyUtils;
import com.hw.common.utils.ip.AddressUtils;
import com.hw.common.utils.ip.IpUtils;
import com.hw.common.utils.ip.UserAgentUtils;
import com.hw.system.admin.mapper.SysLoginLogMapper;
import com.hw.system.admin.pojo.SysLoginLog;
import com.hw.system.admin.pojo.SysUser;
import com.hw.system.admin.service.ISysLoginLogService;
import com.hw.system.admin.service.ISysUserService;
import com.hw.system.admin.vo.SysLoginLogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统访问记录 服务实现类
 * </p>
 *
 * @author 赵士杰
 * @since 2023-11-19 12:20:43
 */
@Service
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLog> implements ISysLoginLogService {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public boolean recordLoginInfo(Long userId, boolean status, String msg) {
        SysLoginLog log = new SysLoginLog();

        log.setUserId(userId);

        String ipAddr = IpUtils.getIpAddr();
        log.setIpAddr(ipAddr);

        String addr = AddressUtils.getRealAddressByIP(ipAddr);
        if (!Arrays.asList(AddressUtils.UNKNOWN, AddressUtils.INTERNAL_IP).contains(addr)) {
            String[] address = addr.split(" ");
            log.setLoginProvince(address[0]);
            log.setLoginCity(address[1]);
        }

        log.setBrowser(UserAgentUtils.getBrowser());
        log.setOs(UserAgentUtils.getPlatform());

        log.setStatus(status);
        log.setMsg(msg);
        return save(log);
    }

    @Override
    public List<SysLoginLogVo> getLoginLogList() {
        LambdaQueryWrapper<SysLoginLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(SysLoginLog::getLogId);
        return list(queryWrapper).parallelStream()
                .map(i -> {
                    SysUser user = sysUserService.getById(i.getUserId());
                    SysLoginLogVo vo = BeanCopyUtils.copyBean(i, SysLoginLogVo.class);
                    vo.setUsername(user.getUsername());
                    return vo;
                })
                .collect(Collectors.toList());
    }

}
